from django.shortcuts import render
from rest_framework.views import APIView, Response
from django.forms.models import model_to_dict
# Create your views here.

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
IN1 = 17
IN2 = 18
IN3 = 27
IN4 = 22

def init():
    GPIO.setup(IN1, GPIO.OUT)
    GPIO.setup(IN2, GPIO.OUT)
    GPIO.setup(IN3, GPIO.OUT)
    GPIO.setup(IN4, GPIO.OUT)

def up():
    GPIO.output(IN1, 0)
    GPIO.output(IN2, 1)
    GPIO.output(IN3, 0)
    GPIO.output(IN4, 1)


def down():
    GPIO.output(IN1, 1)
    GPIO.output(IN2, 0)
    GPIO.output(IN3, 1)
    GPIO.output(IN4, 0)


def turn_left():
    GPIO.output(IN1, 0)
    GPIO.output(IN2, 1)
    GPIO.output(IN3, 1)
    GPIO.output(IN4, 0)


def turn_right():
    GPIO.output(IN1, 1)
    GPIO.output(IN2, 0)
    GPIO.output(IN3, 0)
    GPIO.output(IN4, 1)


init()
class car(APIView):
    def post(self,request):
        type = request.data.get('type',None)
        print(type)
        info = ''
        if not type:
            return Response('失败')
        if int(type) == 1:
            info = '前进'
            up()
        elif int(type) == 2:
            info = '左拐'
            down()
        elif int(type) == 3:
            info = '右拐'
            turn_left()
        elif int(type) == 4:
            info = '后退'
            turn_right()
        elif int(type) == 5:
            info = '停止'
            GPIO.cleanup()
        return Response(info)